package com.xiaoyu.lanling.net;

import android.text.TextUtils;

import com.xiaoyu.base.net.NetworkErrorProcessor;
import com.xiaoyu.base.net.proxy.BaseRequestProxy;

import in.srain.cube.request.FailData;
import in.srain.cube.request.IRequest;
import in.srain.cube.request.JsonData;
import in.srain.cube.util.time.TimeData;

import static com.xiaoyu.net.RequestProvider.CODE_OK;
import static com.xiaoyu.net.RequestProvider.CODE_SUCCESS;

public class JsonRequestProxy extends BaseRequestProxy<JsonData> {

    private static JsonRequestProxy sInstance;

    public JsonRequestProxy() {
    }

    static synchronized public JsonRequestProxy getInstance() {
        if (null == sInstance) {
            sInstance = new JsonRequestProxy();
        }
        return sInstance;
    }

    @Override
    public <T> T processResponse(IRequest<T, JsonData> cubeRequest, int responseCode, String responseText, long rt) throws Exception {
        // TODO @sanshi (Maybe can move to BaseRequestProxy, only if it's general for multi app)
        if (responseCode != CODE_SUCCESS) {
            cubeRequest.setFailData(FailData.fromException(cubeRequest, new Exception(responseText)));
            return null;
        } else if (TextUtils.isEmpty(responseText)) {
            cubeRequest.setFailData(FailData.fromException(cubeRequest, new Exception("result null")));
            return null;
        } else {
            final JsonData jsonData = JsonData.create(responseText);
            TimeData.getInstance().sync(jsonData, rt);
            final int code = jsonData.optInt("code");
            if (code != CODE_OK) {
                return NetworkErrorProcessor.getInstance().processEEE(cubeRequest, code, jsonData.optString("message"));
            } else {
                final JsonData rawData = jsonData.optJson("data");
                if (rawData.optInt("error_code") > 0) { // legacy
                    cubeRequest.setFailData(FailData.fromException(cubeRequest, new Exception(rawData.optString("message"))));
                    return null;
                }
                processExtData(jsonData.optJson("ext_data"));
                return cubeRequest.onDataFromServer(jsonData);
            }
        }
    }

    @Override
    protected void processExtData(JsonData extData) {
        super.processExtData(extData);
    }
}
